const Router = require("koa-router");
const router = new Router();


// const list = require("./list");
//验证码
let code = "";
router.get("/login/code", (ctx, body) => {
  //四位随机验证码  //延迟3秒返回
  //   setTimeout(() => {
  code = new Date().getTime().toString().slice(8, 12);
  console.log(code);
  //   }, 3000);
  //存起来
  ctx.body = code;
});
//手机号+验证码登录
const phone = ["17799999999"];
router.post("/login/phone", (ctx, body) => {
  ctx.body = phone;
  if (ctx.request.body.code == code && ctx.request.body.phone == phone[0]) {
    ctx.body = {
      code1: 200,
      msg: "登录成功",
      data: phone[0],
      token: "1234567890",
    };
  } else {
    ctx.body = { code1: 401, msg: "验证码错误" };
  }
});
let user = [
  {
    username: "admin",
    password: "admin",
    role: "admin",
    nickname: "电费你绕去了问",
    avatar: "https://robohash.org/1231231?set=set5",
  },
  {
    username: "user",
    password: "user",
    role: "user",
    nickname: "服务科老年人服务",
    avatar: "https://robohash.org/576543?set=set5",
  },
  {
    username: "123456",
    password: "123456",
    role: "user",
    nickname: "额哦了你的了可能",
    avatar: "https://robohash.org/gyju564?set=set5",
  },
];

router.post("/login", async (ctx, body) => {
  //   console.log("/login", body, ctx);
  let { username, password } = ctx.request.body;
  let res = user.find((item) => {
    return item.username == username && item.password == password;
  });
  if (res) {
    ctx.body = {
      code: 200,
      msg: "登录成功",
      data: res,
    };
  } else {
    ctx.body = {
      code: 401,
      msg: "登录失败",
    };
  }
});
//存储注册信息
const userinfo = [
  { username: "admin", password: "admin" },
  { username: "user", password: "user" },
  { username: "guge", password: "guge" },
];
router.post("/register", async (ctx, body) => {
  //判断用户名是否已存在
  let { username, password } = ctx.request.body;
  if (userinfo.find((item) => item.username == username)) {
    ctx.body = { code: 401, msg: "用户名已存在" };
  } else {
    userinfo.push({ username, password });
    ctx.body = { code: 200, msg: "注册成功" };
  }
});

module.exports = router;
